package gdufs.lkl.calculator;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class EditCustomFunctionActivity extends AppCompatActivity {

    private EditText nameEditText, paramsEditText, expressionEditText;
    private FunctionStorage functionStorage;
    private CustomFunction currentFunction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_custom_function);

        functionStorage = new FunctionStorage(this);
        nameEditText = findViewById(R.id.editTextFunctionName);
        paramsEditText = findViewById(R.id.editTextFunctionParams);
        expressionEditText = findViewById(R.id.editTextFunctionExpression);
        Button saveButton = findViewById(R.id.buttonSaveFunction);

        long functionId = getIntent().getLongExtra("functionId", -1);
        if (functionId != -1) {
            currentFunction = functionStorage.getFunctions().stream()
                    .filter(f -> f.getId() == functionId)
                    .findFirst()
                    .orElse(null);
            if (currentFunction != null) {
                nameEditText.setText(currentFunction.getName());
                paramsEditText.setText(currentFunction.getParametersAsString());
                expressionEditText.setText(currentFunction.getExpression());
            }
        }

        saveButton.setOnClickListener(v -> saveFunction());
    }

    private void saveFunction() {
        String name = nameEditText.getText().toString().trim();
        String paramsStr = paramsEditText.getText().toString().trim();
        String expression = expressionEditText.getText().toString().trim();

        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, R.string.error_invalid_function_name, Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(expression)) {
            Toast.makeText(this, R.string.error_invalid_expression, Toast.LENGTH_SHORT).show();
            return;
        }

        List<String> params = Arrays.stream(paramsStr.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());

        if (currentFunction == null) {
            functionStorage.addFunction(new CustomFunction(name, params, expression));
        } else {
            currentFunction.setName(name);
            currentFunction.setParameters(params);
            currentFunction.setExpression(expression);
            functionStorage.updateFunction(currentFunction);
        }

        setResult(RESULT_OK);
        finish();
    }
}
